package com.fancyy.scm.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.fancyy.scm.R;
import com.fancyy.scm.base.BaseActivity;
import com.fancyy.scm.base.adapter.BRBaseAdapter;
import com.fancyy.scm.base.annotation.Layout;
import com.fancyy.scm.base.annotation.Translucent;
import com.fancyy.scm.base.http.BRDataListener;
import com.fancyy.scm.base.http.BRDataTransport;
import com.fancyy.scm.bean.CartonInfoItem;
import com.fancyy.scm.bean.ErrorEnum;
import com.fancyy.scm.databinding.ActivityCartonToTrayScanBinding;
import com.fancyy.scm.util.DialogUtil;
import com.fancyy.scm.util.ImgUtil;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import zpSDK.zpSDK.zpBluetoothPrinter;

import static com.fancyy.scm.BRConstant.CARTONTOTARYRESET;
import static com.fancyy.scm.BRConstant.CARTONTOTARYSUBMIT;
import static com.fancyy.scm.BRConstant.GET_USER_SCANLIST;
import static com.fancyy.scm.BRConstant.SCANCARTONTOTARY;
import static com.fancyy.scm.BRConstant.SCANNING_LOAD_ERROR;

@Translucent
@Layout(R.layout.activity_carton_to_tray_scan)
public class CartonToTrayScanActivity extends BaseActivity<ActivityCartonToTrayScanBinding> {

    /**
     * 创建接口对象
     */
    private zpBluetoothPrinter mZpAPI;

    /**
     * 获取当前activity对象
     *
     * @return 返回当前activity对象
     */
    private Activity getActivity() {
        return this;
    }

    BRBaseAdapter adapter = new BRBaseAdapter();
//    List<CartonInfoItem> list = new ArrayList<>();
List<Object> list = new ArrayList<>();

    private boolean isErrorPopUp=false;

    public void onBackButtonClick(View view) {
        finish();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        init();
        setNeedScan(true);
        super.onCreate(savedInstanceState);
        adapter.init(this, R.layout.cartonlistitem, list);
        getDataBinding().listView.setAdapter(adapter);

        String cartonNum = getIntent().getStringExtra("CartonNum");

        getDataBinding().CartonNum.setText(cartonNum);

        loadCortonListListData();
    }
    public  void onConnectPrinterClick(View view){
        Intent intent = new Intent(this, ConnectPrinterActivity.class);
        intent.putExtra("type", 3);
        startActivity(intent);
    }

    private void loadCortonListListData() {
        BRDataTransport.createGet(GET_USER_SCANLIST + "?UserJobNum=" + getBRApplication().getUserInfo().userAccount)
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener<List<CartonInfoItem>>() {
                    @Override
                    public void onSuccess(List<CartonInfoItem> data) {
                        list.clear();
                        if (data != null && data.size() > 0) {
                            list.addAll(data);
                        } else {

                        }
                        adapter.notifyDataSetChanged();
                        getDataBinding().CartonNum.setText(data.size()+"");
                    }
                }, new TypeToken<List<CartonInfoItem>>(){});
    }

    public void onScanningClick(View view) {
        if(!getPDA()) {
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            String code = data.getStringExtra(CodeUtils.RESULT_STRING);
            handleCode(code);
            loadCortonListListData();
        }
    }

    private void handleCode(String code) {
        getDataBinding().scan.setText(code);
        BRDataTransport.create(SCANCARTONTOTARY)
                .addParam("barcode", getDataBinding().scan.getText().toString())
                .addParam("OperateUserName", getBRApplication().getUserInfo().name)
                .addParam("OperateUserAccount", getBRApplication().getUserInfo().userAccount)
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener<List<CartonInfoItem>>() {
                    @Override
                    public void onSuccess(List<CartonInfoItem> data) {
                        list.clear();
                        if (data != null && data.size() > 0) {
                            list.addAll(data);
                        } else {
                            showToast("No data be found");
                        }
                        adapter.notifyDataSetChanged();
                        getDataBinding().CartonNum.setText(data.size()+"");
                        playSound(R.raw.success);

                    }

                    @Override
                    public void onFail(int status, String failMessage) {
                        playSound(R.raw.error);
//                        isErrorPopUp = true;
//                        DialogUtil.showAlert(self(), "Error", failMessage, "OK", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//                                dialogInterface.dismiss();
//                                loadErrorCodes();
//                            }
//                        });
                        //showToast(failMessage);

                        new AlertDialog.Builder(CartonToTrayScanActivity.this).setTitle("Error")
                                .setMessage(failMessage)
                                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).show();

                    }
                }, new TypeToken<List<CartonInfoItem>>(){});
    }

    @Override
    public void doScan(String data) {
        if(!isErrorPopUp)
            handleCode(data);
//        closeScan();
    }

    String remark;

    public void onResetClick(View view) {
        BRDataTransport.createPost(CARTONTOTARYRESET + "?UserJobNum=" +  getBRApplication().getUserInfo().userAccount)
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener() {
                    @Override
                    public void onSuccess(Object data) {
                        getDataBinding().scan.setText("");
                        getDataBinding().CartonNum.setText("");
                        loadCortonListListData();
                        showToast("Reset Success");
                    }
                });
    }

    /**
     * 初始化打印控件
     */
    private void init() {
        //打印控件不为null,进行实例化
        if (mZpAPI == null) {
            mZpAPI = new zpBluetoothPrinter(getActivity());
        }
    }

    public void onTraySubmitClick(View view) {
        BRDataTransport.create(CARTONTOTARYSUBMIT)
                .addParam("OperateUserName", getBRApplication().getUserInfo().name)
                .addParam("OperateUserAccount", getBRApplication().getUserInfo().userAccount)
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener() {
                    @Override
                    public void onSuccess(Object data) {
                        String picData = ((LinkedTreeMap) data).get("pic").toString();
//                        showToast("Full Match Success");
                        try {
                            boolean isprintsucess = mZpAPI.drawBitmap(ImgUtil.stringToBitmap(picData), 0, 0, 600, 650, 0, 1);
                            if (isprintsucess)
                                showToast("Print Success");
                            else
                                showToast("Print Failed");

                        } catch (Exception ex) {
                            showToast("Print Failed");
                        }
                        finally {
                            loadCortonListListData();
                        }

                    }

                    @Override
                    public void onFail(int status, String failMessage) {
                        showToast(failMessage);
                    }
                });
    }


    List<ErrorEnum> errorData;
    private void loadErrorCodes() {
        BRDataTransport.createGet(SCANNING_LOAD_ERROR + "?EnumCategory=7")
                .addProgressing(self(), getString(R.string.Progressing))
                .execute(new BRDataListener<List<ErrorEnum>>() {
                    @Override
                    public void onSuccess(List<ErrorEnum> data) {
                        errorData = data;
                        getDataBinding().submit.setVisibility(View.VISIBLE);
                        TextView t = findViewById(R.id.code);
                        t.setText(data.get(0).enumName);
                        remark = data.get(0).enumCode;
                    }
                }, new TypeToken<List<ErrorEnum>>(){});
    }

    public void onCancelClick(View view) {
        remark = null;
        getDataBinding().submit.setVisibility(View.GONE);
        isErrorPopUp = false;
    }

    public void onErrorCodeClick(View view) {
        DialogUtil.showList(self(), "Error Item", errorData, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                remark = errorData.get(which).enumCode;
                TextView t = findViewById(R.id.code);
                t.setText(errorData.get(which).enumName);
                dialogInterface.dismiss();
            }
        }, true);
    }

}
